package com.a1anwang.okble.demo.ability;

import com.a1anwang.okble.beacon.OKBLEBeacon;
import com.a1anwang.okble.beacon.OKBLEBeaconManager;
import com.a1anwang.okble.demo.ResourceTable;
import com.a1anwang.okble.demo.base.BaseAbility;
import com.a1anwang.okble.demo.common.MyLinkedHashMap;

import com.a1anwang.okble.demo.widget.HeadDefaultComponent;
import com.a1anwang.okble.demo.widget.IRefresh;
import com.a1anwang.okble.demo.widget.RefreshComponent;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

public class ScanBeaconAbility extends BaseAbility {
    private OKBLEBeaconManager scanManager;
    private ListContainer listview;
    private ItemProvider provider;
    private MyLinkedHashMap<String, OKBLEBeacon> scanedResults;
    private boolean isFirstResume = true;
    private Image btnLeft;
    private Text tvTitle;

    @Override
    public boolean isFullScreen() {
        return false;
    }

    @Override
    public void setContentLayout() {
        setUIContent(ResourceTable.Layout_ability_scan_ibeacon);
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        scanManager.stopScan();
    }

    @Override
    protected void onActive() {
        super.onActive();
        scanManager.startScanBeacon();
    }

    @Override
    protected void onStop() {
        super.onStop();
        scanManager.stopScan();
    }

    @Override
    public void beforeInitView() {
        scanedResults = new MyLinkedHashMap<>();
        scanManager = new OKBLEBeaconManager(this);
        scanManager.setBeaconScanCallback(scanCallBack);
    }

    @Override
    public void initView() {
        btnLeft = (Image) findComponentById(ResourceTable.Id_btn_left);
        tvTitle = (Text) findComponentById(ResourceTable.Id_tv_title);
        tvTitle.setText("Scan iBeacon");
        btnLeft.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                onBackPressed();
            }
        });
        setHeadVisibility(Component.VISIBLE);

        listview = (ListContainer) findComponentById(ResourceTable.Id_listview_scan);
        // 获取到刷新组件
        RefreshComponent myView = (RefreshComponent) findComponentById(ResourceTable.Id_myView);
        // 设置头部刷新样式,可自定义样式
        HeadDefaultComponent headDefaultComponent = new HeadDefaultComponent(this);
        // 添加样式到头部
        myView.setHeadComponent(headDefaultComponent);
        // 设置刷新回调
        myView.setRefreshListener(new IRefresh.RefreshListener() {
            @Override
            public void onRefresh() {

                new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
                    @Override
                    public void run() {
                        scanedResults.clear();
                        provider.notifyDataChanged();
                        scanManager.startScanBeacon();
                        // 数据更新完  结束掉刷新
                        myView.refreshFinish();
                    }
                }, 500);
            }

            @Override
            public boolean enableRefresh() {
                return false;
            }
        });
        provider = new ItemProvider(ScanBeaconAbility.this);
        listview.setItemProvider(provider);
    }

    @Override
    public void afterInitView() {

    }

    @Override
    public void onClickEvent(Component v) {
    }

    OKBLEBeaconManager.OKBLEBeaconScanCallback scanCallBack = new OKBLEBeaconManager.OKBLEBeaconScanCallback() {
        @Override
        public void onScanBeacon(OKBLEBeacon beacon) {
            listview.setEnabled(true);
            int value[] = scanedResults.put(beacon.getIdentifier(), beacon);
            new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
                @Override
                public void run() {
                    if (value[1] == 1) {

                        // 这是新增数据
                        provider.notifyDataChanged();
                    } else {

                        // 这是重复数据,刷新rssi
                        int index = value[0];
                        updatePosition(index);
                    }
                }
            });
        }
    };

    private void updatePosition(int posi) {
        int visibleFirstPosi = listview.getFirstVisibleItemPosition();
        int visibleLastPosi = listview.getLastVisibleItemPosition();
        if (posi >= visibleFirstPosi && posi <= visibleLastPosi) {
            Component view = listview.getComponentAt(posi - visibleFirstPosi);
            if (view != null) {
                ViewHolder holder = (ViewHolder) view.getTag();
                if (holder != null) {
                    holder.tvRssi.setText(scanedResults.get(posi).getRssi() + "");
                }
            }
        }
    }

    /**
     * ItemProvider 适配器
     *
     * @since 2021-05-14
     */
    private class ItemProvider extends BaseItemProvider {

        private Context context;

        ItemProvider(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return scanedResults == null ? 0 : scanedResults.size();
        }

        @Override
        public Object getItem(int position) {
            if (scanedResults != null && position >= 0 && position < scanedResults.size()) {
                return scanedResults.get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public Component getComponent(int position, Component convertView, ComponentContainer parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_list_item_beacon, null, false);
                holder.tvName = (Text) convertView.findComponentById(ResourceTable.Id_tv_name);
                holder.tvUuid = (Text) convertView.findComponentById(ResourceTable.Id_tv_uuid);
                holder.tvMajor = (Text) convertView.findComponentById(ResourceTable.Id_tv_major);
                holder.tvMinor = (Text) convertView.findComponentById(ResourceTable.Id_tv_minor);
                holder.tvRssi = (Text) convertView.findComponentById(ResourceTable.Id_tv_rssi);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            OKBLEBeacon beacon = scanedResults.get(position);
            holder.tvName.setText(beacon.getName() == null ? "[null]" : beacon.getName());
            holder.tvUuid.setText(beacon.getUuid());
            holder.tvMajor.setText("" + beacon.getMajor());
            holder.tvMinor.setText("" + beacon.getMinor());
            holder.tvRssi.setText("" + beacon.getRssi());
            return convertView;
        }
    }

    protected static final class ViewHolder {
        Text tvName;
        Text tvUuid;
        Text tvMajor;
        Text tvMinor;
        Text tvRssi;
    }
}
